package com.qinsoft.business.onsale.bean;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

public class ArrayHandler implements TypeHandler<String[][]>
{

    @Override
    public String[][] getResult(ResultSet rs, String columnName) throws SQLException
    {
        return this.getStringArray(rs.getString(columnName));
    }

    @Override
    public String[][] getResult(ResultSet rs, int columnIndex) throws SQLException
    {
        return this.getStringArray(rs.getString(columnIndex));
    }

    @Override
    public String[][] getResult(CallableStatement cs, int columnIndex) throws SQLException
    {
        return this.getStringArray(cs.getString(columnIndex));
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, String[][] parameter, JdbcType jdbcType) throws SQLException
    {
        StringBuffer result = new StringBuffer();
        for (String[] value : parameter)
        {
            for (String v : value)
            {
                result.append(v).append(",");
            }
            result.deleteCharAt(result.length() - 1);
            result.append(";");
        }
        result.deleteCharAt(result.length() - 1);
        ps.setString(i, result.toString());
    }

    private String[][] getStringArray(String columnValue)
    {
        String[][] array = new String[7][24];
        if (columnValue == null) return null;
        else
        {
            String[] value = columnValue.split(";");
            for (int i = 0; i < value.length; i++)
            {
                String[] v = value[i].split(",");
                for (int j = 0; j < v.length; j++)
                {
                    array[i][j] = v[j];
                }
            }
        }
        return array;
    }

}
